<script setup lang="ts">

import {useUserStore} from "@/store/user";
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

// 本地读取用户列表（只包含账户+头像） 用户动态显示头像
const users = ref([])
// 是否登录，用于样式切换
const is_login = ref(true)
// 用户状态
const userStore = useUserStore()
// 路由实例
const router = useRouter()

// 在挂载后读取用户列表
onMounted(() => {
  users.value = JSON.parse(localStorage.getItem('users')) || []
})

// 根据本地账户更改头像
const getAvatar = (e: Event) => {
  users.value.forEach(user => {
    if (user.account === e.target.value) {
      userStore.user.avater = user.avater
    }
  })
}
// 登录
const on_login = async () => {
  const is_add = await userStore.on_login()
  if (is_add) {
    ElMessage({
      message: '登录成功',
      type: 'success',
      plain: true,
    })
  }
}
// 注册
const on_register = async () => {
  const is_add = await userStore.on_register()
  if (is_add) {
    ElMessage({
      message: '注册成功',
      type: 'success',
      plain: true,
    })
  }
}
// 样式更改为注册
const to_register = () => {
  is_login.value = false
}
// 样式更改为登录
const to_login = () => {
  is_login.value = true
}
// 去往重置密码页面
const to_resetPassword = async () => {
  await router.push('/resetPassword')
}
</script>

<template>
  <div class="w-full h-svh flex justify-center items-center bg-blue-500">
    <div class="w-[220px] h-[300px] bg-blue-200">
      <div class="flex justify-center m-3 mt-5">
        <el-avatar :size="50" :src="userStore.user.avater"/>
      </div>
      <el-form
          label-width="auto"
          :model="userStore.user"
          style="max-width: 600px"
          class="m-4"
      >
        <el-form-item>
          <el-input v-model="userStore.user.account" @input="getAvatar" placeholder="输入账户"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="userStore.user.password" placeholder="输入密码"/>
        </el-form-item>
      </el-form>
      <div class="m-3">
        <el-button v-if="is_login" class="w-full" type="primary" @click="on_login">重置</el-button>
        <el-button v-else class="w-full" type="primary" @click="on_register">注册</el-button>
      </div>
      <div>
        <div class="flex justify-between m-10 text-[10px] text-blue-500">
          <div v-if="is_login" class="hover:text-blue-700 cursor-pointer" @click="to_register">注册账户</div>
          <div v-else class="hover:text-blue-700 cursor-pointer" @click="to_login">登录账户</div>
          <div class="hover:text-blue-700 cursor-pointer" @click="to_resetPassword">重置密码</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>